package cn.edu.zust.lxy.wangke_backend.controller;

import cn.edu.zust.lxy.wangke_backend.common.Result;
import cn.edu.zust.lxy.wangke_backend.mapper.AppointmentMapper;
import cn.edu.zust.lxy.wangke_backend.mapper.BookMapper;
import cn.edu.zust.lxy.wangke_backend.mapper.BorrowMapper;
import cn.edu.zust.lxy.wangke_backend.mapper.UserMapper;
import cn.edu.zust.lxy.wangke_backend.model.Book;
import cn.edu.zust.lxy.wangke_backend.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author keboom
 * @date 2021/6/14 12:36
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private BorrowMapper borrowMapper;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        boolean status = userMapper.insert(user);
        if (!status) {
            return new Result(500, "注册失败", null);
        }
        return new Result(201, "注册成功", user.getUser_name());
    }

    @GetMapping("/login")
    public Result login(String user_name, String user_password) {
        User user = userMapper.findByName(user_name);
        if (user == null) {
            return new Result(501, "没有此用户",null);
        }
        if (user.getUser_password().equals(user_password)) {
            return new Result(200, "登录成功", null);
        } else {
            return new Result(210, "密码不对！", null);
        }
    }

    /**
     * 为了简单，直接把预约的书和借阅的书放到一起了
     * @return
     */
    @GetMapping("/personCenter")
    public Result<List<Book>> personalCenter(String username) {
        Integer userId = userMapper.getIdByName(username);
        List<Integer> bookIdList1 = appointmentMapper.getIdByUserId(userId);

        List<Integer> bookIdList2 = borrowMapper.getIdByUserId(userId);
        bookIdList2.addAll(bookIdList1);
        List<Book> books = new ArrayList<>();
        for (Integer integer : bookIdList2) {
            books.add(bookMapper.getBookById(integer));
        }
        return new Result<List<Book>>(200,"查询成功",books);
    }
}
